﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using SLua;

[CustomLuaClass]
[System.Serializable]
public class Config
{
    #region Instance

    static Config ms_Instance;
    public static Config Instance { get { return ms_Instance; } }

    #endregion

    // 游戏名(用于Android本地推送的标题)
    public static string GameName { get { return Instance.config.GameName; } }
    // 包名
    public static string BundleId { get { return Instance.config.BundleId; } }
    // 更新目录
    public static string UpdateURL { get { return Instance.config.UpdateURL; } }
    // 更新服目录名
    public static string UpdateName { get { return Instance.config.UpdateName; } }
    // 高清资源目录名
    public static string HDResName { get { return Instance.config.HDResName; } }

    // 基础版本,如1.02.003的基础版本是1.02.001
    public static string VersionBase
    {
        get
        {
            return Instance.config.Version;
        }
    }

    // 版本号
    static string ms_version;
    public static string Version
    {
        get
        {
            if (string.IsNullOrEmpty(ms_version))
            {
                ms_version = PlayerPrefs.GetString(APP_CURRENT_VERSION, Instance.config.Version);
            }
            return ms_version;
        }
        set
        {
            ms_version = value;
            PlayerPrefs.SetString(APP_CURRENT_VERSION, value);
        }
    }
    // 版本号(如:{"1", "01", "001"}})
    public static string[] VersionBits { get { return Version.Split('.'); } }

    // ios_release_101
    public static string UpdateVersionName
    {
        get
        {
            string[] versions = VersionBits;
            return string.Format("{0}_release_{1}{2}", UpdatePlatformName, versions[0], versions[1]);
        }
    }

    // 开发者模式(指向测试包 xuzhihui at 17.01.25)
    public static bool IsDeveloper { get { return Instance.config.IsDeveloper; } }
    // 发布类型
    public static ReleaseType Release { get { return Instance.config.Release; } }

    // 位数类型 1-32bit; 2-64bit
    [DoNotToLua]
    public static LuaArchType LuaArch
    {
        get
        {
#if UNITY_IOS
			return System.IntPtr.Size == 8 ? LuaArchType.BIT_64 : LuaArchType.BIT_32;
#else
            return LuaArchType.BIT_32;
#endif
        }
    }

    // 平台类型及名称
#if UNITY_EDITOR
    public const PlatformType Platform = PlatformType.Editor;
    public const string PlatformName = "editor";
#elif UNITY_IOS
    public const PlatformType Platform = PlatformType.iOS;
    public const string PlatformName = "ios";
#elif UNITY_ANDROID
    public const PlatformType Platform = PlatformType.Android;
    public const string PlatformName = "android";
#else
    public const PlatformType Platform = PlatformType.Editor;
    public const string PlatformName = "pc";
#endif

#if UNITY_IOS
    public const string UpdatePlatformName = "ios";
#elif UNITY_ANDROID
    public const string UpdatePlatformName = "android";
#else
    public const string UpdatePlatformName = "editor";
#endif

    #region 设备信息

    public static string DeviceModel;
    public static string SystemVersion;
    public static string UserId = "";
    public static string DeviceID = "";		// 设备唯一ID
    public static bool SupportInstancing;
    #endregion

    // 帧率
    public const int FrameRate = 60;

    // 路径
    static string m_OriginalFullPath;
    static string m_StreamingAssetsPath;
    static string m_UnpackDataPath;
    static string m_UpdateDataPath;
    static string m_CachePath;
    static string m_TempPath;
    static string m_UIAssetsPath;                   // ui在Assets下的路径
    static string m_DataAssetsPath;                 // Data在Assets下的路径
    static string m_ArtAssetsPath;                  // Art在Assets下的路径
    static string m_DBPath;                         // 本地数据库路径
    public static string ORIGINAL_FULLPATH
    {
        get
        {
            if (string.IsNullOrEmpty(m_OriginalFullPath))
            {
                m_OriginalFullPath = string.Format("{0}/{1}", Application.dataPath, ORIGINAL_PATH);
            }
            return m_OriginalFullPath;
        }
    }

    public static string STREAMING_ASSETS_PATH
    {
        get
        {
            if (string.IsNullOrEmpty(m_StreamingAssetsPath))
            {
                m_StreamingAssetsPath = string.Format("{0}/data", Application.streamingAssetsPath);
            }
            return m_StreamingAssetsPath;
        }
    }

    public static string UNPACK_DATA_PATH
    {
        get
        {
            if (string.IsNullOrEmpty(m_UnpackDataPath))
            {
                m_UnpackDataPath = string.Format("{0}/data", Application.persistentDataPath);
            }
            return m_UnpackDataPath;
        }
    }

    public static string UPDATE_DATA_PATH
    {
        get
        {
            if (string.IsNullOrEmpty(m_UpdateDataPath))
            {
                m_UpdateDataPath = string.Format("{0}/update", Application.persistentDataPath);
            }
            return m_UpdateDataPath;
        }
    }

    public static string CACHE_PATH
    {
        get
        {
            if (string.IsNullOrEmpty(m_CachePath))
            {
                m_CachePath = string.Format("{0}/cache", Application.persistentDataPath);
            }
            return m_CachePath;
        }
    }

    public static string TEMP_PATH
    {
        get
        {
            if (string.IsNullOrEmpty(m_TempPath))
            {
                m_TempPath = string.Format("{0}/temp", Application.persistentDataPath);
            }
            return m_TempPath;
        }
    }

    public static string UI_ASSETS_PATH
    {
        get
        {
            if (string.IsNullOrEmpty(m_UIAssetsPath))
            {
                m_UIAssetsPath = string.Format("{0}/{1}/{2}", "Assets", ORIGINAL_PATH, UI_PATH);
            }
            return m_UIAssetsPath;
        }
    }

    public static string UI_ATLAS_PATH
    {
        get
        {
            return UI_ASSETS_PATH + "/atlas_padding.asset";
        }
    }

    public static string DATA_ASSETS_PATH
    {
        get
        {
            if (string.IsNullOrEmpty(m_DataAssetsPath))
            {
                m_DataAssetsPath = string.Format("{0}/{1}", "Assets", ORIGINAL_PATH);
            }
            return m_DataAssetsPath;
        }
    }

    public static string ART_ASSETS_PATH
    {
        get
        {
            if (string.IsNullOrEmpty(m_ArtAssetsPath))
            {
                m_ArtAssetsPath = string.Format("{0}/{1}", "Assets", ART_PATH);
            }
            return m_ArtAssetsPath;
        }
    }

    public static string DB_PATH
    {
        get
        {
            if (string.IsNullOrEmpty(m_DBPath))
            {
                m_DBPath = string.Format("{0}/db", Application.persistentDataPath);
            }
            return m_DBPath;
        }
    }

    [DoNotToLua]
    public const string LUA_PATH = "Lua";               // Lua目录
    [DoNotToLua]
    public const string LUA_MAIN = "main";              // Lua入口文件名
    [DoNotToLua]
    public const string LUA_PACKAGE = "luaout";         // Lua打包文件名
    [DoNotToLua]
    public const string LUA_PATCH = "luapatch";         // Lua补丁文件名
    [DoNotToLua]
    public const string MANIFEST_NAME = "data";         // AssetBundle清单文件名
    [DoNotToLua]
    public const string AB_SUFFIX = "unity3d";          // Assetbundle后缀
#if UNITY_IOS
    [DoNotToLua]
    public const bool AB_COMPRESS = false;              // 是否开启AssetBundle压缩
#else
    [DoNotToLua]
    public const bool AB_COMPRESS = false;              // 是否开启AssetBundle压缩
#endif
#if UNITY_IOS
    [DoNotToLua]
	public const bool DATA_COMPRESS = true;            	// 是否开启数据压缩
#else
    [DoNotToLua]
    public const bool DATA_COMPRESS = true;            	// 是否开启数据压缩
#endif
    [DoNotToLua]
    public const bool DATA_UNCOMPRESS_INRUNTIME = true; // 是否开启运行时解压

    [DoNotToLua]
    public const bool LUA_DATA = false;	            	// 使用LuaData

    [DoNotToLua]
    public const string SOUND_SUFFIX = "mp3";           // 音效后缀
    [DoNotToLua]
    public const string MUSIC_SUFFIX = "mp3";           // 音乐后缀
    [DoNotToLua]
    public const int SOUND_SOURCE_COUNT = 24;           // 音效数量

    [DoNotToLua]
    public const string KEY_LANGUAGE = "KEY_LANGUAGE";           //多语言存储KEY
    public const string KEY_MUSIC_VOLUME = "KEY_MUSIC_VOLUME";   //背景音乐音量
    public const string KEY_SOUND_EFFECT_VOLUME = "KEY_SOUND_EFFECT_VOLUME"; //音效音量
    public const string UI_PATH = "ui";

    public const string ORIGINAL_PATH = "Data";    	 // 资源路径(Assets下的相对路径) 
    public const string ART_PATH = "Art";
    public const bool IsTR = false;
    public const bool IsMainUILTR = false;           // 主UI是否右到左

    [DoNotToLua]
    public ConfigData config;

    // 节点
    public Transform Root;                              // 游戏根节点
    public Transform RootAudio;                         // 游戏声音节点
    public Canvas MainUI;                               // 主UI
    public Canvas BlurUI;                               // 模糊UI
    public CanvasScaler MainUIScaler;                   // 主UI CanvasScaler
    public CanvasScaler BlurUIScaler;                   // 模糊UI CanvasScaler
    public RectTransform MainUITran;
    public RectTransform MainUIRoot;
    public RectTransform BlurUIRoot;

    public Transform RootCache;                         // 对象缓存根节点
    public Camera WorldCamera;                             // UI相机
    public Camera UICamera;                             // UI相机
    public Camera BlurCamera;                           // 模糊相机

    // 开关
    public bool CheckUnpack { get { return DATA_COMPRESS && UseAssetBundle; } }			// 是否需要启动解压
    public bool CheckUpdate { get { return config.CheckUpdate; } }       				// 检测更新
    public bool IsTestIphoneX = false;                  // 测试IphoneX分辨率
    public bool UseCity2dBuildPosConfig = true;         // 测试内城UI坐标配置
    public bool UseAssetBundle = true;                 // 使用AssetBundle
    public bool NativeMenuShow = false;                 // 显示C#测试菜单
    public bool UseTexturePacker = true;                // 使用TexturePacker
                                                        // 是否开启日志
    public bool LogEnable
    {
        get
        {
            return LogLevel == Debuger.Level.LOG;
        }
        set
        {
            LogLevel = value ? Debuger.Level.LOG : Debuger.Level.ERROR;
            Debuger.LogLevel = LogLevel;
        }
    }
    public bool ResourceSplit { get { return config.ResourceSplit && Platform == PlatformType.Android; } }
    [DoNotToLua]
    public bool ConsoleShow = false;                    // 显示控制台信息
    [DoNotToLua]
    public bool MemoryShow = false;                    	// 显示内存信息
    [DoNotToLua]
    public bool NeverSleep = false;                     // 屏幕常亮
    public bool Profiler { get { return IsDeveloper; } }// 开启性能分析
    public bool ManualGC;                               // 自动GC

    public bool DumpEnable = true;
    public Debuger.Level LogLevel = Debuger.Level.LOG;  // 日志等级(输出这个级别及以上)
    public string Language { get; set; }
    public long MinNeedDiskSize { get { return DATA_COMPRESS ? Instance.config.MinNeedDiskSize : 0L; } }    // 需要磁盘空间
    public bool iPhoneX { get { return m_iPhoneX; } set { m_iPhoneX = value; } }
    public bool iPadScreen { get { return m_iPadScreen; } set { m_iPadScreen = value; } }

    [Range(0, 120)]
    public int AssetCacheTime = 10;                     // 资源缓存时间(秒,0立即删除)

    // 解压线程系数(线程数=核心数*系数)
    [HideInInspector]
    public int UnpackThreadFactor = 2;

    [DoNotToLua]
    public static string APP_CURRENT_VERSION = "__OE_INNER_CURRENT_VERSION__";

    // 缓存Lua持久化数据,当lua虚拟机重启之后,还需要用的数据,json格式
    public static string LuaPersistentData = "";

    private bool m_iPhoneX = false;
    private bool m_iPadScreen = false;

    public int width { get; set; }
    public int height { get; set; }

    public int realWidth { get; set; }
    public int realHeight { get; set; }

    [DoNotToLua]
    public void Init()
    {
        ms_Instance = this;
        realWidth = Screen.width;
        realHeight = Screen.height;
        //UseAssetBundle = true;

#if !UNITY_EDITOR && UNITY_STANDALONE
		m_iPhoneX = true;

		float scale = GameDefine.StandaloneScale;
		Screen.SetResolution((int)(1125 * scale), (int)(2436 * scale), false);
#endif

#if !UNITY_EDITOR
        // 非编辑器,一律使用Asset Bundle
        UseAssetBundle = true;
        // 非编辑器,一律使用配置
		UseCity2dBuildPosConfig = true;
        // 非编辑器,只打印Error及以上级别的日志
		if (Release == ReleaseType.RELEASE){
        	LogLevel = Debuger.Level.ERROR;
		}
#endif
        DeviceModel = SystemInfo.deviceModel;
        SystemVersion = SystemInfo.operatingSystem;
        DeviceID = SystemInfo.deviceUniqueIdentifier;
        SupportInstancing = SystemInfo.supportsInstancing;

        //设置多语言
        if (PlayerPrefs.HasKey(KEY_LANGUAGE))
        {
            Language = PlayerPrefs.GetString(KEY_LANGUAGE);
        }
        else
        {
            // 这里开发阶段直接用中文, 上线前即使是IsDeveloper也不能直接用中文, 要用 Language = Instance.config.Language;
            if (IsDeveloper)
            {
                Language = "zh_cn";
            }
            else
            {
                Language = Instance.config.Language;
            }
        }

        WorldCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
        Root = GameObject.Find("GameMain").transform;
        UICamera = Root.Find("UICamera").GetComponent<Camera>();

        MainUITran = Root.Find("Canvas") as RectTransform;
        MainUI = MainUITran.GetComponent<Canvas>();
        MainUIRoot = Root.Find("Canvas/Root") as RectTransform;
    }
}